<template>
  <div class="page">
    <div class="title">
      <div class="icon">
        <img src="@/assets/logo.png" alt="">
      </div>
      <div class="name">Baby Baby Love</div>
    </div>
    <div class="main bt11">
      <div class="titl">质押中记录</div>
      <div class="item">
        <div class="label">NFT分红池地址</div>
        <div class="value" @click="proxy.copy(mainContractAddress)">{{ proxy.plusXing(mainContractAddress, 4, 6, '.', 4)
        }}</div>
      </div>
      <div class="item">
        <div class="label">参与质押时间</div>
        <div class="value">{{ report.startTime }}</div>
      </div>
      <div class="item">
        <div class="label">合约质押时长</div>
        <div class="value">{{ report.time }}天</div>
      </div>
      <div class="item">
        <div class="label">质押消耗</div>
        <div class="value">{{ report.nftNumber }}NFT/{{ report.frmNumber }}BBL</div>
      </div>
    </div>
    <div class="bosAdd">
      <div class="jijin">
        <div class="name">级别</div>
        <div class="address">{{ userLv(level) }}</div>
      </div>
    </div>
    <div class="main bt11 mainNet">
      <div class="titl">链上资产</div>
      <div class="slide">
        <div class="blac pd0">
          <div class="left">
            <div class="nas">NFT余额</div>
            <div class="num">{{ nftBalanceNet }}</div>
          </div>
          <van-button color="linear-gradient(90deg, #52A952, #40A5DB)" :icon="getImageUrls('zhuan')"
            @click="show = true; type = 1; isNet = true" :disabled="nftBalanceNet ? false : true">
            转让
          </van-button>
        </div>
        <div class="blac">
          <div class="left">
            <div class="nas">BBL余额</div>
            <div class="num">{{ frmBalanceNet }}</div>
          </div>
          <van-button color="linear-gradient(90deg, #52A952, #40A5DB)" :icon="getImageUrls('zhuan')"
            @click="show = true; type = 0; isNet = true" :disabled="frmBalanceNet ? false : true">
            转让
          </van-button>
        </div>
      </div>
    </div>
    <div class="main">
      <div class="titl">资产余额</div>
      <div class="slide">
        <div class="blac pd0">
          <div class="left">
            <div class="nas">NFT余额</div>
            <div class="num">{{ propertyDis.nftBalance }}</div>
          </div>
          <div class="rig">
            <van-button color="linear-gradient(90deg, #52A952, #40A5DB)" @click="Withdrawal(1)"
              :disabled="propertyDis.nftBalance ? false : true" :loading="wloadingNft">
              提现
            </van-button>
            <van-button color="linear-gradient(90deg, #52A952, #40A5DB)" :icon="getImageUrls('zhuan')"
              @click="show = true; type = 1; isNet = false" :disabled="propertyDis.nftBalance ? false : true">
              转让
            </van-button>
          </div>
        </div>
        <div class="blac van-hairline--top">
          <div class="left">
            <div class="nas">BBL余额</div>
            <div class="num">{{ propertyDis.frmBalance }}</div>
          </div>
          <div class="rig">
            <van-button color="linear-gradient(90deg, #52A952, #40A5DB)" @click="Withdrawal(0)"
              :disabled="propertyDis.frmBalance ? false : true" :loading="wloadingFrim">
              提现
            </van-button>
            <van-button color="linear-gradient(90deg, #52A952, #40A5DB)" :icon="getImageUrls('zhuan')"
              @click="show = true; type = 0; isNet = false" :disabled="propertyDis.frmBalance ? false : true">
              转让
            </van-button>
          </div>
        </div>
      </div>
    </div>
    <div class="btns">
      <van-button class="shouquan" block color="linear-gradient(90deg, #52A952, #40A5DB)"
        @click="router.push('Withdrawal')">BBL提现记录</van-button>
      <van-button class="shouquan" block color="linear-gradient(90deg, #52A952, #40A5DB)"
        @click="net">区块链发放记录</van-button>
    </div>
    <div class="main pd15">
      <van-list v-model:loading="loading" :finished="finished" finished-text="加载完成" @load="onLoad">
        <div class="item" v-for="(item, index) in list" :key="index">
          <div class="label">{{ item.createdTime }}</div>
          <div class="value">+{{ Number(item.amount.toFixed(4)) + item.tokenName }} {{ item.type ? '动态' : '静态' }}产出</div>
        </div>
      </van-list>
    </div>
  </div>
  <van-popup v-model:show="show" closeable round>
    <div class="box">
      <div class="time">{{ type == 1 ? 'NFT' : 'BBL' }}转账</div>
      <div class="img">
        <img src="@/assets/zhuanT.png" alt="">
      </div>
      <van-field class="fild" clearable v-model="transferAddress" label="" placeholder="输入您的地址" />
      <van-field class="fild" clearable v-model="transferNumber" :type="inputType" label="" placeholder="输入转让数量" />
      <van-button class="shouquan" block color="linear-gradient(90deg, #52A952, #40A5DB)"
        @click="confirm">确认转让</van-button>
    </div>
  </van-popup>
  <Tabbar :active="2"></Tabbar>
</template>
<script setup name="index" lang="ts">
import Tabbar from '@@/Tabbar';
import {
  mainContractAddress
} from '@/utils/casinoContract'
import { ref, getCurrentInstance, onMounted, computed, reactive, watch } from 'vue'
import contractStore from '@/store/modules/contract'
import { getNowFormatDate } from '@/utils/filter.js'
import { Toast } from 'vant';
import * as BigToSmall from "@/utils/BNUtils.js";
import { stakeReport, accessSelf, accessTransfer, claimFrm, claimNft, rewardRecordPage, addressSelf } from '@/api/request'
import { useRoute, useRouter } from 'vue-router';
import { Dialog } from 'vant';

interface data {
  createdTime: string,
  tokenName: string,
  type: number, // 1动态0静态
  amount: number
}
// const VanDialog = Dialog.Component;
const { proxy } = getCurrentInstance() as any;
const appStore = contractStore()
const router = useRouter()
const BalanceFRM = computed(() => appStore.BalanceFRM)
const BalanceNFT = computed(() => appStore.BalanceNFT)
const empowerFRM = computed(() => appStore.empowerFRM)
const empowerNFT = computed(() => appStore.empowerNFT)
const web3 = computed(() => appStore.WEB3)
const contractInstance = computed(() => appStore.contractInstance)
const token = computed(() => appStore.token)
const nft = computed(() => appStore.nft)
const address = computed(() => appStore.address)
const show = ref(false)
const transferAddress = ref('')
const transferNumber = ref('')
const type = ref(0)
const page = ref(1)
const loading = ref(false);
const finished = ref(false);
const list = ref<data[]>([]);
const wloadingNft = ref(false)
const wloadingFrim = ref(false)
const isNet = ref(false)
const level = ref(0)
const inputType = computed(() => type.value == 1 && isNet.value ? 'digit' : 'number')
const nftBalanceNet = computed(() => appStore.BalanceNFT)
const frmBalanceNet = computed(() => appStore.BalanceFRM)
const propertyDis = reactive({
  nftBalance: 0,
  frmBalance: 0
})
const report = ref({
  "startTime": "-",
  "time": 0,
  "nftNumber": 0,
  "frmNumber": 0
})
onMounted(() => {
  proxy.userAuthorization(appStore, (res: boolean) => {
    if (res) {
      init()
    }
  })
})

const init = async () => {
  let res = await stakeReport()
  console.log(res)
  if (res.status == 200 && JSON.stringify(res.data) != '{}') {
    report.value = res.data
  }
  let ret = await addressSelf()
  if (ret.status == 200) {
    level.value = ret.data.level
  }
  querySelf()
}
const userLv = (res: number) => {
  switch (res) {
    case 0:
      return '包身工'
    case 1:
      return '一星黄金农民工'
    case 2:
      return '二星翡翠小村长'
    case 3:
      return '三星宝石生产队长'
    case 4:
      return '四星钻石公社社长'
    case 5:
      return '五星荣誉地主'
    default:
      return '包身工'
  }
}
const querySelf = async () => {
  let val = await accessSelf()
  if (val.status == 200 && JSON.stringify(val.data) != '{}') {
    propertyDis.frmBalance = val.data.frmBalance
    propertyDis.nftBalance = val.data.nftBalance
  }
}
const queryBalance = async () => {
  let usdts = await token.value.methods.balanceOf(address.value).call()
  let usdtRes = Number(BigToSmall.chufa(usdts, 18))
  appStore.SET_BalanceFrm(usdtRes)

  let gks = await nft.value.methods.balanceOf(address.value, 0).call()
  let gkRes = Number(gks)
  appStore.SET_BalanceNFT(gkRes)
}
const confirm = async () => {
  console.log('confirm', isNet.value)
  if (!transferAddress.value || !transferNumber.value) {
    return
  }
  if (isNet.value) {
    const isValidAddress = (address: string) => {
      return web3.value.utils.isAddress(address)
    }
    if (isValidAddress(transferAddress.value)) {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0,
      });
      let fn = '' as any
      if (type.value == 0) {
        let amount = BigToSmall.pow(transferNumber.value, 18)
        fn = token.value.methods.transfer(transferAddress.value, amount)
      } else {
        fn = nft.value.methods.safeTransferFrom(address.value, transferAddress.value, '0', transferNumber.value, '0x00')
      }
      try {
        await fn.send({
          from: address.value
        })
        Toast.clear()
        Toast('转账成功')
        queryBalance()
      } catch (error) {
        Toast.clear()
        Toast('转账失败')
      }
    } else {
      Toast('地址输入错误')
    }
  } else {
    let res = await accessTransfer({
      toAddress: transferAddress.value,
      amount: +transferNumber.value,
      type: type.value
    })
    console.log(res)
    if (res.status == 200) {
      Toast('转让成功')
      transferAddress.value = ''
      transferNumber.value = ''
      querySelf()
    }
  }
  show.value = false
}
const Withdrawal = async (val: number) => {
  let message = ''
  if (val) {
    // NFT
    message = '提现数量：' + propertyDis.nftBalance + 'NFT</br>销毁数量：1FRM'
  } else {
    message = '提现数量：' + propertyDis.frmBalance + 'BBL</br>销毁数量：' + (Number((+propertyDis.frmBalance * 0.06).toFixed(4))) + 'BBL'
  }
  Dialog.confirm({
    title: '提示',
    message: message,
    confirmButtonColor: '#63A0FE',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    allowHtml: true,
    cancelButtonColor: '#767676'
  })
    .then(async () => {
      let res = '' as any
      if (val) {
        res = await claimNft()
      } else {
        res = await claimFrm()
      }
      if (res.status == 200) {
        btnStatus(val, true)
        console.log(res)
        let parms = res.data
        try {
          contractInstance.value.methods.claim(parms.tokenAddress, parms.address, parms.amount, parms.sign).send({
            from: address.value
          }).then((res: any) => {
            Toast('提现成功')
            btnStatus(val, false)
            querySelf()
          }).catch((err: any) => {
            console.log(err)
            btnStatus(val, false)
          })
        } catch (error) {
          btnStatus(val, false)
        }
      }
    })
    .catch(() => {
      // on cancel
    });
}
const btnStatus = (type: number, boole: boolean) => {
  if (type) {
    wloadingNft.value = boole
  } else {
    wloadingFrim.value = boole
  }
}
const net = () => {
  let NODE_ENV = import.meta.env.MODE == 'production' ? true : false
  if (NODE_ENV) {
    location.href = `https://testnet.bscscan.com/address/${mainContractAddress}`
  } else {
    location.href = `https://testnet.bscscan.com/address/${mainContractAddress}`
  }
}
const onLoad = async () => {
  let res = await rewardRecordPage({ page: page.value })
  let data = res.data
  if (res.status == 200) {
    if (page.value == 1) {
      list.value = []
    }
    loading.value = false;
    data.records.forEach((element: { loading: boolean; }) => {
      element.loading = false
    });
    list.value = list.value.concat(data.records)
    if (data.records.length < 20) {
      finished.value = true;
    } else {
      page.value++
    }
  }
};
const getImageUrls = (name: string) => new URL(`../../assets/${name}.png`, import.meta.url).href
</script>
<style scoped lang="less">
.box {
  display: flex;
  flex-direction: column;
  padding: 20px 24px;

  .fild {
    height: 44px;
    border: 1px solid #CACACA;
    border-radius: 10px;
    margin-bottom: 14px;
    font-size: 17px;

    :deep(input::-ms-input-placeholder) {
      text-align: center;
      font-size: 17px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #6E6E6E;
    }

    :deep(input::-webkit-input-placeholder) {
      text-align: center;
      font-size: 17px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #6E6E6E;
    }
  }

  .img {
    width: 137px;
    height: 118px;
    margin: 13px 61px 26px 61px;
  }

  .time {
    font-size: 25px;
    font-family: PingFang SC;
    font-weight: 800;
    color: #000000;
  }
}

.page {
  background: #E9E9E9;
  min-height: calc(100vh - 50px);
  padding: 0 13px;
  padding-bottom: 50px;

  .bt11 {
    margin-bottom: 11px;
  }

  .pd0 {
    padding-top: 0 !important;
  }

  .btns {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    column-gap: 11px;
    margin-bottom: 16px;

    button {
      font-size: 18px !important;
    }
  }

  .mainNet {
    .slide {
      flex-direction: row !important;
      justify-content: space-around;

      .blac {
        flex-direction: column;
        margin-bottom: 0 !important;
        padding-top: 0 !important;

        .left {
          align-items: center;
          margin-bottom: 10px;
        }
      }
    }
  }

  .bosAdd {
    display: flex;
    align-items: center;
    margin-top: 16px;
    margin-bottom: 15px;

    .copy {
      height: 44px;
      background: #47A7A4;
      border-radius: 15px;
      padding: 0 20px;
      font-size: 19px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #FFFFFF;
      line-height: 44px;
    }

    .jijin {
      height: 44px;
      background: #FFFFFF;
      border-radius: 15px;
      flex: 1;
      padding: 0 13px;
      display: flex;
      align-items: center;
      display: flex;
      justify-content: space-between;

      .name {
        font-size: 15px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #575757;
        margin-right: 14px;
        white-space: pre;
      }

      .address {
        font-size: 15px;
        font-family: PingFang SC;
        font-weight: 800;
        color: #000000;

        .van-cell {
          padding-left: 0;
          padding-right: 0;
        }
      }
    }
  }

  .main {
    padding: 20px;
    background: #FFFFFF;
    border-radius: 15px;

    .titl {
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: 800;
      color: #000000;
      line-height: 16px;
      margin-bottom: 15px;
    }

    .slide {
      display: flex;
      flex-direction: column;

      .blac:last-child {
        margin-bottom: 0;
      }

      .blac {
        display: flex;
        justify-content: space-between;
        margin-bottom: 19px;
        padding-top: 20px;

        .left {
          display: flex;
          flex-direction: column;

          .nas {
            font-size: 15px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #767676;
            line-height: 28px;
          }

          .num {
            font-size: 18px;
            font-family: PingFang SC;
            font-weight: 800;
            color: #000000;
          }
        }

        .rig {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          column-gap: 5px;

          button {
            height: 44px;
            border-radius: 15px;
          }
        }
      }
    }

    .item {
      line-height: 28px;
      display: flex;
      justify-content: space-between;

      .label {
        font-size: 15px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #767676;
        white-space: pre;
      }

      .value {
        font-size: 15px;
        font-family: PingFang SC;
        font-weight: 800;
        color: #000000;
      }
    }
  }

  .pd15 {
    padding: 15px;
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 15px;
    padding-bottom: 15px;

    .icon {
      width: 48px;
      height: 48px;
      margin-right: 6px;
    }

    .name {
      font-size: 19px;
      font-family: PingFang SC;
      font-weight: 800;
      color: #000000;
    }
  }
}
</style>